package com.itmk.web.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmk.web.sys_menu.entity.AssignTreeParm;
import com.itmk.web.sys_menu.entity.AssignTreeVo;
import com.itmk.web.sys_menu.entity.MakeMenuTree;
import com.itmk.web.sys_menu.entity.SysMenu;
import com.itmk.web.sys_menu.service.SysMenuService;
import com.itmk.web.sys_user.entity.SysUser;
import com.itmk.web.sys_user.mapper.SysUserMapper;
import com.itmk.web.sys_user.service.SysUserService;
import com.itmk.web.sys_user_role.entity.SysUserRole;
import com.itmk.web.sys_user_role.service.SysUserRoleSrevice;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserRoleSrevice sysUserRoleSrevice;

    @Resource
    private SysMenuService sysMenuService;

    @Transactional
    @Override
    public void saveUser(SysUser user) {
        //插入用户信息
        int i = this.baseMapper.insert(user);
        //设置用户角色
        if (i > 0) {
            String[] split = user.getRoleId().split(",");
            if (split.length > 0) {
                List<SysUserRole> roles = new ArrayList<>();
                for (int j = 0; j < split.length; j++) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(user.getUserId());
                    sysUserRole.setRoleId(Long.parseLong(split[j]));
                    roles.add(sysUserRole);
                }
                //保存用户角色表
                sysUserRoleSrevice.saveBatch(roles);
            }
        }

    }

    @Transactional
    @Override
    public void updateUser(SysUser user) {
        //编辑用户信息
        int i = this.baseMapper.updateById(user);
        //设置用户角色
        if (i > 0) {
            String[] split = user.getRoleId().split(",");
            //删除用户原来的角色，重新创建
            QueryWrapper<SysUserRole> query = new QueryWrapper<>();
            query.lambda().eq(SysUserRole::getUserId, user.getUserId());
            sysUserRoleSrevice.remove(query);
            //设置用户角色
            if (split.length > 0) {
                List<SysUserRole> roles = new ArrayList<>();
                for (int j = 0; j < split.length; j++) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(user.getUserId());
                    sysUserRole.setRoleId(Long.parseLong(split[j]));
                    roles.add(sysUserRole);
                }
                //保存用户角色表
                sysUserRoleSrevice.saveBatch(roles);
            }
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        //删除用户
        int i = this.baseMapper.deleteById(userId);
        if (i > 0) {
            //删除用户角色
            QueryWrapper<SysUserRole> query = new QueryWrapper<>();
            query.lambda().eq(SysUserRole::getUserId, userId);
            sysUserRoleSrevice.remove(query);
        }

    }

    @Override
    public AssignTreeVo getAssignTree(AssignTreeParm parm) {
        //查询用户的信息,是否超级管理员
        SysUser user = this.baseMapper.selectById(parm.getUserId());
        List<SysMenu> menuList = null;
        //判断是否超级管理员
        if(StringUtils.isNotEmpty(user.getIsAdmin()) && "1".equals(user.getIsAdmin())){
            //是超级管理员，查询所有菜单数据
            menuList = sysMenuService.list();
        }else{
            menuList = sysMenuService.getMenuByUserId(parm.getUserId());
        }
        //组装权限树
        List<SysMenu> makeTree = MakeMenuTree.makeTree(menuList, 0L);
        //查询角色所有的菜单
        List<SysMenu> roleIds = sysMenuService.getMenuByRoleId(parm.getRoleId());
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(roleIds).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(item->{
                    ids.add(item.getMenuId());
                });
        //组装返回数据
        AssignTreeVo vo = new AssignTreeVo();
        vo.setCheckList(ids.toArray());
        vo.setMenuList(makeTree);
        return vo;
    }
}
